package com.example.soa_exp2.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.soa_exp2.Domain.Borrow;
import com.example.soa_exp2.Domain.Goods;
import com.example.soa_exp2.Mapper.GoodsMapper;
import com.example.soa_exp2.Service.GoodsService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private Goods goods;

    @Resource
    private GoodsMapper goodsMapper;

    @Override
    public List<Goods> getGoodsList(){
        return goodsMapper.selectList(null);
    }

    @Override
    public Goods getGoodsById(String id){
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", id);
        return goodsMapper.selectOne(wrapper);
    }

    @Override
    public List<Goods> getGoodsByName(String name){
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.like("goods_name", name);
        return goodsMapper.selectList(wrapper);
    }

    @Override
    public int addGoods(Goods goods) {
        List<Goods> goodsList = getGoodsList();
        for (Goods goods_a: goodsList) {
            if(Objects.equals(goods_a.getGoods_id(), goods.getGoods_id())){
                return 0;
            }
        }
        return goodsMapper.insert(goods);
    }

    @Override
    public int deleteGoodsStock(String goods_id, Long stock){
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goods_id);
        Goods goods = goodsMapper.selectOne(wrapper);
        Long now_stock= goods.getStock();
        if(now_stock < stock){
            return 0;
        }else{
            UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("goods_id",goods_id);
            goods.setStock(now_stock - stock);
            return goodsMapper.updateById(goods);
        }
    }

    @Override
    public int addGoodsStock(String goods_id, Long stock){
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goods_id);
        Goods goods = goodsMapper.selectOne(wrapper);
        Long now_stock = goods.getStock();

        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("goods_id", goods_id);
        goods.setStock(now_stock + stock);
        return goodsMapper.updateById(goods);
    }

    @Override
    public int updateGoods(Goods goods){
        return goodsMapper.updateById(goods);
    }
    @Override
    public int deleteGoods(String goods_id){
        return goodsMapper.deleteById(goods_id);
    }
}
